import { useMemo, useState, useEffect } from 'react'
import { Tabs, SearchBar, Button, Checkbox, Tag, Image, Toast } from 'antd-mobile'
import { getGoodsList, GoodsItem } from '../../api/goods'
import './index.less'

export default function GoodsCenterPage() {
    const [keyword, setKeyword] = useState('')
    const [selected, setSelected] = useState<Record<string, boolean>>({})
    const [goodsList, setGoodsList] = useState<GoodsItem[]>([])
    const [loading, setLoading] = useState(false)
    const [activeTab, setActiveTab] = useState('all')

    const tabMap = {
        all: '全部商品',
        op: '低价好物',
        hot: '精选货源'
    }

    const fetchGoodsList = async (tab: string, searchKeyword: string, page: number) => {
        setLoading(true)
        try {
            const tagName = tabMap[tab as keyof typeof tabMap] || '全部商品'
            const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
            const {result} = await getGoodsList({
                // userId: '790899243',
                userId: userInfo.userId,
                tagName,
                keyword: searchKeyword,
                pageNum: page,
                pageSize: 10
            })
            console.log("🚀 ~ fetchGoodsList ~ result:", result)

            if (result.body.code === 200) {
                if (page === 1) {
                    setGoodsList(result.body.data)
                } else {
                    setGoodsList(prev => [...prev, ...result.body.data])
                }
            } else {
                Toast.show({ content: result.body.msg || '获取商品列表失败' })
            }
        } catch (error) {
            Toast.show({ content: '网络请求失败' })
        } finally {
            setLoading(false)
        }
    }

    useEffect(() => {
        fetchGoodsList(activeTab, keyword, 1)
    }, [activeTab]) // eslint-disable-line react-hooks/exhaustive-deps

    const handleSearch = () => {
        fetchGoodsList(activeTab, keyword, 1)
    }

    const handleTabChange = (key: string) => {
        setActiveTab(key)
        setSelected({})
    }

    const allChecked = useMemo(() =>
        goodsList.length > 0 && goodsList.every(i => selected[i.itemId.toString()]),
        [selected, goodsList])

    const selectedCount = useMemo(() =>
        Object.values(selected).filter(Boolean).length,
        [selected])

    const toggleAll = (checked: boolean) => {
        const next: Record<string, boolean> = {}
        goodsList.forEach(i => { next[i.itemId.toString()] = checked })
        setSelected(next)
    }

    const toggleOne = (id: string, checked: boolean) => {
        setSelected(prev => ({ ...prev, [id]: checked }))
    }

    const formatPrice = (price: number) => {
        return (price / 100).toFixed(2)
    }

    return (
        <div className="goods-page">
            <div className="goods-top">
                <div className="tabs">
                    <Tabs activeKey={activeTab} onChange={handleTabChange}>
                        <Tabs.Tab title='全部商品' key='all' />
                        <Tabs.Tab title='低价好物' key='op' />
                        <Tabs.Tab title='精选货源' key='hot' />
                    </Tabs>
                </div>
                {/* <div className="category-row">
                    <div className="left">
                        <span>全部类目</span>
                        <DownOutline fontSize={12} />
                    </div>
                    <div className="right">
                        <span className="bulk-link">批量铺货</span>
                    </div>
                </div> */}
                <div className="search-row">
                    <div className='search-row-left'>
                        <SearchBar value={keyword} onChange={setKeyword} placeholder='输入搜索关键词' clearable={false} />
                        <Button size='small' color='primary' className='search-btn' onClick={handleSearch} loading={loading}>搜索</Button>
                    </div>
                    <span className="bulk-link">批量铺货</span>
                </div>
            </div>

            <div className="goods-list">
                {goodsList.map(item => (
                    <div className="goods-item" key={item.itemId}>
                        <div className="left">
                            <Checkbox checked={!!selected[item.itemId.toString()]} onChange={val => toggleOne(item.itemId.toString(), val)} />
                        </div>
                        <div className="thumb">
                            <Image src={item.imgUrl} width={80} height={80} fit='cover' style={{ borderRadius: 6 }} />
                        </div>
                        <div className="content">
                            <div className="title">{item.title}</div>
                            <div className="badges">
                                {item.serviceList.map((service, idx) => (
                                    <Tag key={idx} color='warning' fill='outline' className='b'>{service.name}</Tag>
                                ))}
                            </div>
                            <div className="meta">
                                <div className="price">¥ {formatPrice(item.minPrice)}</div>
                                <Button size='mini' color='primary'>铺货</Button>
                            </div>
                        </div>
                    </div>
                ))}
                {loading && <div style={{ textAlign: 'center', padding: '20px' }}>加载中...</div>}
            </div>

            <div className="goods-bottom">
                <div className="left">
                    <Checkbox checked={allChecked} onChange={toggleAll}>全选</Checkbox>
                    <span className="count">已选:{selectedCount}件</span>
                </div>
                <Button color='primary' className='bulk-btn'>批量铺货</Button>
            </div>

            <div className="goods-bottom-space" />
        </div>
    )
}
